from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
# 从Django的认证模块中导⼊密码哈希处理函数
# make_password: ⽤于将明⽂密码转换为加密哈希值
# check_password: ⽤于验证明⽂密码与已加密密码哈希值是否匹配
from django.contrib.auth.hashers import make_password, check_password
from .models import SysUser
from rest_framework_simplejwt.settings import api_settings
# ⽤于处理JWT（JSON Web Token）的刷新令牌功能。
from rest_framework_simplejwt.tokens import RefreshToken
import datetime
from rest_framework.permissions import AllowAny


# Create your views here.

class RegisterView(APIView):
    """
    用户注册
    """

    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        email = request.data.get('email', '')
        phonenumber = request.data.get('phonenumber', '')

        # 检查必要字段
        if not username or not password:
            return Response({
                'code': 400,
                'message': '用户名和密码不能为空',
            }), status.HTTP_400_BAD_REQUEST
        if SysUser.objects.filter(username=username).exists():
            return Response({
                'code': 400,
                'message': '用户名已存在!'
            })

        # 创建用户
        try:
            user = SysUser.objects.create(
                username=username,
                password=make_password(password),
                email=email,
                phonenumber=phonenumber,
                status=0,
                create_time=datetime.datetime.now(),
                update_time=datetime.datetime.now(),
            )
            # 注意：phonenumber字段需要在User模型中扩展才能保存

            return Response({
                'code': 200,
                'message': '注册成功',
                'data': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email
                }
            })
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'注册失败: {str(e)}',
                'data': {}
            })



class LoginView(APIView):
    """
    用户登录
    """
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        print( username, password)

        # 检查必要字段
        if not username or not password:
            return Response({
                'code': 400,
                'message': '用户名和密码不能为空',
            }, status=status.HTTP_400_BAD_REQUEST)


        # 创建用户
        try:
            user = SysUser.objects.get(username=username)
            if check_password(password, user.password): # 检查密码(密码正确)
                # 生成JWT令牌 刷新令牌
                # RefreshToken.for_user(user)(用户信息表)---刷新令牌

                # 为用户生成刷新令牌
                refresh = RefreshToken.for_user(user)

                # 获取刷新令牌
                refresh_token = str(refresh)
                # 打印刷新令牌
                print(refresh_token)

                # 获取访问令牌
                access_token = str(refresh.access_token)
                # 打印访问令牌
                print(access_token)
                return Response({
                    'code': 200,
                    'message': '登录成功',
                    'data': {
                        'token': access_token,
                        'user': {
                            'id': user.id,
                            'username': user.username,
                            'email': user.email
                        }
                    }
                })

            else:
                return Response({
                    'code': 400,
                    'message': '密码错误!'
                })

            # 注意：phonenumber字段需要在User模型中扩展才能保存
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'登录失败: {str(e)}',
                'data': {}
            })
